var _LO = (function() {
    this.controlset=null;
    var oTable,onInit=false,source,dataAdapter,jqxLinkGrid='#jqxLinkGrid';
	var datafields = [
        {name: 'Id', type: 'int'},
        {name: 'Thumb'},
        {name: 'Title'},{name: 'Alias'},
        {name: 'Position',type: 'int'},
        {name: 'Status',type: 'bool'},
        {name: 'Insert', type: 'date'},
        {name: 'Update', type: 'date'},
    ];
	var columns = [
        /*{
            text: '', dataField: 'Id', width: 32, filterable: false, sortable: false,editable: false,
            cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                var str = "";
                if (value && value > 0) {
                    try {
                        //value = $.parseJSON(value);
                        str += "\
                            <span style='margin: 4px 4px 4px 4px; float: left;line-height: 16px;' class=\"icon-link\" onclick=\"_LO.onSetNewsLink(" + row + ");\"  title='Edit:" + value + "'></span>\
                        ";
                        
                    } catch (e) {
                    }
                }

                return str;
            }
        },*/
        /*{text: ''     , dataField: 'Thumb'   ,width:40,filterable:false ,sortable: false,
            cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                if(value==undefined || value=='')
                    return '';
                else{
                    
                    return '<img onError="this.src = \'/libraries/images/22/picture.png\'" class="cellthumb" height="32" src="' + (value) + '"/>';
                }
            }
        },*/
        {
            text: 'Title'       , dataField: 'Title',
			cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties,_data) {
				//var _data = $(jqxLinkGrid).jqxGrid('getrowdata', row);
				
				var str = '<div class="rnode" style="overflow: hidden; text-overflow: ellipsis;text-align: left;line-height:24px;padding-left:2px">';
				str+='<img style="left:0;top:0;margin-right:4px" onError="this.src = \'/libraries/images/22/picture.png\'" class="cellthumb" height="32" src="' + (_data.Thumb) + '"/><b>'+value+'</b><div class="act"><span title="Get link" class="icon-link" onclick="_LO.onSetNewsLink('+row+')"></span></div>';
				str+='</div>';
                return str;
			}
        },
    ];
    return {
        onInit  :   function(){
            if(onInit) return;onInit=true;
            _CONFIG.CATEFILLTER='';
            _CONFIG.tBINDING_URI=base_url + 'cms/cp/project/binding/';
            
            _LO.creategrid();
			
        },
        onChangeSource:function(cats){
			if(cats===_CONFIG.CATEFILLTER)return;
            _CONFIG.CATEFILLTER=cats;
			source.url = _CONFIG.tBINDING_URI+_CONFIG.CATEFILLTER;
            this.onRefresh();
        },
		creategrid:function(){
			//jqxLinkGrid
			source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.tBINDING_URI+_CONFIG.CATEFILLTER,
                filter: function() {
                    $(jqxLinkGrid).jqxGrid('updatebounddata', 'filter');
                },
                sort: function() {
                    $(jqxLinkGrid).jqxGrid('updatebounddata');
                },
                root: 'rows',
                beforeprocessing: function(data) {
                    
                }
            };
            dataAdapter = new $.jqx.dataAdapter(source, {
				beforeSend: function (xhr) {
					$('#jqxNewsSearchbtn').off('click');
				},
				loadComplete: function () {
					$('#jqxNewsSearchbtn').on('click',function(){
						_LO.onFillter('Title',$('#jqxNewsSearchtxt').val());
					});
					$('#jqxNewsSearchtxt').focus()
				},
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
			$(jqxLinkGrid).jqxGrid({
                width: '100%', //autoheight:true,
                height: 295,
                source: dataAdapter,
                theme: theme, sortable: true,
                //filterable: true,
                //autoshowfiltericon: true,
                //showfilterrow: true,
                //rowsheight:34,
                showemptyrow: true,
                columns: columns,
                selectionmode: 'singlecell',
                virtualmode: true,
                //groupable: true,
                rendergridrows: function(){ return dataAdapter.records; },
                pageable: true,
                pagesize: 100,
                pagesizeoptions: ['100', '200', '500', '1000'],
                ready: function() {
                    var $refresh = $('<div type="button"  title="Refresh" style="margin-left: 0px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/view_refresh.png"/></div>');
                    var $option = $('<div type="button"  title="Option" style="margin-left: 0px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/option.gif"/></div>');
                    $refresh.click(function(){
                        _LO.onRefresh();
                    });
                    $option.prependTo($(jqxLinkGrid+' .jqx-grid-pager>div'));
                    $refresh.prependTo($(jqxLinkGrid+' .jqx-grid-pager>div'));
                    $("#jqxNewsSearchtxt").keyup(function(event){
						if(event.keyCode == 13){
							$("#jqxNewsSearchbtn").click();
						}
					});
                }

            });
		},
        onOpenPopup:   function(control){
            this.controlset=control;
            if($('#link-choose').length===0){
                $('body').append('<div id="link-choose">\n\
                <div class="" style="width: 480px;position: relative;height: 320px;">\
                    <div style="overflow: hidden;height: 320px;">\
						<div style="border:1px solid #ccc;border-bottom:0;position:relative">\
							<input id="jqxNewsSearchtxt" placeholder="Type to Search..." class="base_row" style="height:24px;margin:0;padding:0;border:0"/>\
							<div id="jqxNewsSearchbtn" style="position:absolute;right:0;top:0;height:100%;width:60px;line-height:24px;text-align:center;font-weight:bold">Search</div>\
						</div>\
                        <div id="jqxLinkGrid" ></div>\
                    </div>\
                </div></div>');
            }
            bckdialog({
                title:'Link',
                message:$('#link-choose'),
                buttons: [
                    {
                        text    :'Cancel',
                        class   :'base_button base_red base-small-border-radius',
                        click   : function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            }).open();
            _LO.onInit();
        },
        onClose:function(){
            $('#link-choose').dialog("close");
        },
        onSetNewsLink:function(_row){
			var _data = $(jqxLinkGrid).jqxGrid('getrowdata', _row);
            var newsid=_data.Id;
            var newsalias=_data.Alias;
            if(this.controlset!==null)
                $(this.controlset).val('/project/'+newsid+'-'+newsalias);
            this.onClose();
        },
        onSetCateLink:function(that){
            var cateid=$(that).parents('.cnode').data('cateid');
            var catealias=$(that).parents('.cnode').data('catealias');
            if(this.controlset!==null)
                $(this.controlset).val('/danh-muc/'+cateid+'-'+catealias);
            this.onClose();
        },
        onLoadNews:function(that){
            $(jqxLinkGrid).jqxGrid('updatebounddata');
        },
		onFillter: function(datafield, filtervalue) {
            if (filtervalue == '') {
                $(jqxLinkGrid).jqxGrid('removefilter', datafield, true);
                return;
            }
            var filtertype = 'stringfilter';
            var filtergroup = new $.jqx.filter();
            var filter_or_operator = 1;
            var filtercondition = 'contains';
            var filter = filtergroup.createfilter(filtertype, filtervalue, filtercondition);
            filtergroup.addfilter(filter_or_operator, filter);

            //$(grid_element).jqxGrid('clearfilters');
            // add the filters.
            $(jqxLinkGrid).jqxGrid('addfilter', datafield, filtergroup);
            // apply the filters.
            $(jqxLinkGrid).jqxGrid('applyfilters');
        },
		onRefresh:function(){
            $(jqxLinkGrid).jqxGrid('updatebounddata');
        }
	};
}());